package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.config.properties.AliOSSUtil;
import com.jsb.laundry.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.model.dto.AddCodeRequest;
import com.jsb.laundry.utils.RedisUtil;
import io.swagger.annotations.Api;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;


import javax.annotation.Resource;
import java.io.*;
import java.util.concurrent.TimeUnit;

@Api(tags = {"分享二维码"})
@RestController
@RequestMapping("/addCode/")
public class WxQRCode {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private WechatMiniPayProperties wechatMiniPayProperties;



    //接口文档 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/createQRCode.html
    @PostMapping("codes")
    public WebResponse QRCode(@RequestBody AddCodeRequest addCodeRequest) { //0: 去用户小程序端首页,1:去骑手端首页
        String code = "";
        if ("0".equals(addCodeRequest.getT())) {
            String access_token = redisUtil.getCacheObject("wx_user_access_token");
            if (JSBUtil.isEmptyString(access_token)){
                access_token = "";
            }
            code = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + access_token;
        } else {
            String access_token = redisUtil.getCacheObject("wx_rider_access_token");
            code = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + access_token;
        }

        JSONObject jsonStr = new JSONObject();
        if ("0".equals(addCodeRequest.getT())) { // 0:去用户小程序端首页1:去骑手端首页
            jsonStr.put("path", String.format("/pages/clothes/index?userId=%s&userType=%s", addCodeRequest.getAppUserId(), addCodeRequest.getUserType()));
        } else {
            //去骑手端
            jsonStr.put("path", String.format("/pages/roborder/index?userId=%s&userType=%s", addCodeRequest.getAppUserId(), addCodeRequest.getUserType()));
        }
        jsonStr.put("width", "280px");
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(code);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)   //连接服务区主机超时时间
                .setConnectionRequestTimeout(60000) //连接请求超时时间
                .setSocketTimeout(60000).build(); //设置读取响应数据超时时间
        //为httppost请求设置参数
        httpPost.setConfig(requestConfig);
        //将上传参数放到entity属性中
        httpPost.setEntity(new StringEntity(JSON.toJSONString(jsonStr), "UTF-8"));
        //添加头信息
        httpPost.addHeader("Content-type", "text/xml");
        String result = "";
        String resCodeImg = null;
        try {
            //发送请求
            httpResponse = httpClient.execute(httpPost);
            //从相应对象中获取返回内容
            HttpEntity entity = httpResponse.getEntity();
            InputStream content = entity.getContent();
            byte[] bytes = InputStreamToByte(content);
            System.out.println(bytes);
            result = Base64.encodeBase64String(bytes);

            MultipartFile multipartFile = base64ToMultipartFile(result);
            resCodeImg = AliOSSUtil.uploadFile(multipartFile, "code");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return WebResponse.successData(resCodeImg);
    }

    public static MultipartFile base64ToMultipartFile(String base64String) throws IOException {
        byte[] content = Base64.decodeBase64(base64String);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "file", "wechatQRCodeBase64Str.png", ContentType.APPLICATION_OCTET_STREAM.toString(), content);
        return mockMultipartFile;
    }

    /**
     * 输入流转字节流
     */
    private byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int ch;
        while ((ch = in.read(buffer)) != -1) {
            bytestream.write(buffer, 0, ch);
        }
        byte data[] = bytestream.toByteArray();
        bytestream.close();
        return data;
    }

    private String Img(String base) throws IOException {

        BASE64Decoder decoder = new BASE64Decoder();
        String name = System.getProperties().get("os.name").toString();
        String path = "";
        if (name.toLowerCase().contains("windows")) {      // 在windows操作系统上运行jar时，文件路径处理
            path = "c:\\a.png";
        } else if (name.toLowerCase().contains("linux")) {   // 在Linux操作系统上运行jar时，文件路径处理
            path = "/root/jsb/jsb-sp/jsbConfig/a.png";
        } else {// 在windows操作系统上用idea运行时,文件路径处理
            path = "c:\\a.png";
        }
        byte[] bytes = decoder.decodeBuffer(base);
        File file = new File(path);
        FileOutputStream fos = new FileOutputStream(file);

        fos.write(bytes);

        fos.flush();
        MultipartFile multipartFile = fileToMultipartFile(file);
        String code = AliOSSUtil.uploadFile(multipartFile, "code");
        fos.close();
        return code;
    }

    /**
     * @param file
     * @Description: file 转 MultipartFile
     * @return: MultipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }


}
